package cn.mitool.core.crypto.digest;

import cn.mitool.core.util.ByteUtil;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * SHA-256摘要
 *
 * @author dragon
 * @version 1.0
 * @date 2024/7/2 10:49
 */
public class SHA256 {

    /**
     * SHA-256摘要
     *
     * @param data 数据
     * @return SHA-256哈希值
     */
    public String digestHex(String data) throws NoSuchAlgorithmException {
        /* Java SHA-256 */
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(data.getBytes(StandardCharsets.UTF_8));
        // 计算哈希值并转换为16进制字符串
        byte[] digest = messageDigest.digest();

        return ByteUtil.byteToHexString(digest);
    }

    /**
     * SHA-256摘要
     *
     * @param data 数据
     * @return SHA-256哈希值
     */
    public String digestHex(byte[] data) throws NoSuchAlgorithmException {
        /* Java SHA-256 */
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(data);
        // 计算哈希值并转换为16进制字符串
        byte[] digest = messageDigest.digest();

        return ByteUtil.byteToHexString(digest);
    }

    /**
     * SHA-256摘要
     *
     * @param data 数据
     * @return SHA-256哈希值
     */
    public String digestHex(InputStream data) throws IOException, NoSuchAlgorithmException {
        /* Java SHA-256 */
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(data.readAllBytes());
        // 计算哈希值并转换为16进制字符串
        byte[] digest = messageDigest.digest();
        return ByteUtil.byteToHexString(digest);
    }

}
